package com.df.hitime.common.config;

import com.df.hitime.common.AdminException;
import com.df.hitime.common.Constants;
import com.df.hitime.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;

/**
 * @Description:
 * @Author: huangwl
 * @CreateDate: 2018/11/30 10:09
 */
@Slf4j
@Aspect
@Component
public class LoginAop {

    @Resource
    HttpServletRequest request;

    @Pointcut("@annotation(com.df.hitime.common.config.LoginAuth)")
    public void before() {

    }

    @Before("before()")
    public void checkLogin(JoinPoint joinPoint) throws AdminException {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        log.info("method:" + methodSignature.getMethod());
        log.info("判断是否登录");
        String token=request.getHeader("token");
        log.info("login aop 获取token:"+token);
      /*  HttpSession session=request.getSession();
        log.info("sessionId:"+session.getId());
        AdminManagement adminManagement= (AdminManagement) session.getAttribute(Constants.ADMIN_LOGIN_SESSION);
        if(adminManagement==null){
            throw new AdminException("登录已超时，请重新登录");
        }*/
      if(StringUtils.isEmpty(token)){
          throw new AdminException("登录已超时，请重新登录");
      }
        HashMap<String, HashMap<String, Object>> sysMap = Constants.adminMap;
        if (sysMap.get(token) != null) {
            HashMap<String, Object> mm = sysMap.get(token);
            Date date = (Date) mm.get("date");
            if (new Date().getTime() >= date.getTime()) { //超时
                throw new AdminException("登录已超时，请重新登录");
            }
            mm.put("date", DateUtils.addData(1));
            sysMap.put(token, mm);
        } else {
            throw new AdminException("登录已超时，请重新登录");
        }
    }

}
